package com.doctor.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.HttpServletResponse;

import com.doctor.common.core.domain.R;
import com.doctor.common.utils.SecurityUtils;
import com.doctor.web.domain.DoctorScheduled;
import com.doctor.web.service.IDoctorScheduledService;
import eu.bitwalker.useragentutils.browser.SafariUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.doctor.common.annotation.Log;
import com.doctor.common.core.controller.BaseController;
import com.doctor.common.core.domain.AjaxResult;
import com.doctor.common.enums.BusinessType;
import com.doctor.web.domain.Appointment;
import com.doctor.web.service.IAppointmentService;
import com.doctor.common.utils.poi.ExcelUtil;
import com.doctor.common.core.page.TableDataInfo;

/**
 * 预约记录Controller
 *
 * @author Li
 * @date 2024-05-15
 */
@RestController
@RequestMapping("/maincode/appointment")
public class AppointmentController extends BaseController {
    @Autowired
    private IAppointmentService appointmentService;

    /**
     * 查询预约记录列表
     */
    @PreAuthorize("@ss.hasPermi('maincode:appointment:list')")
    @GetMapping("/list")
    public TableDataInfo list(Appointment appointment) {
        if (SecurityUtils.getUserId() != 1L){
            appointment.setDoctorId(SecurityUtils.getUserId());
        }
        startPage();
        List<Appointment> list = appointmentService.selectAppointmentList(appointment);
        return getDataTable(list);
    }

    /**
     * 导出预约记录列表
     */
    @PreAuthorize("@ss.hasPermi('maincode:appointment:export')")
    @Log(title = "预约记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Appointment appointment) {
        List<Appointment> list = appointmentService.selectAppointmentList(appointment);
        ExcelUtil<Appointment> util = new ExcelUtil<Appointment>(Appointment.class);
        util.exportExcel(response, list, "预约记录数据");
    }

    /**
     * 获取预约记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('maincode:appointment:query')")
    @GetMapping(value = "/{appointmentId}")
    public AjaxResult getInfo(@PathVariable("appointmentId") Long appointmentId) {
        return success(appointmentService.selectAppointmentByAppointmentId(appointmentId));
    }

    /**
     * 新增预约记录
     */
    @PreAuthorize("@ss.hasPermi('maincode:appointment:add')")
    @Log(title = "预约记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Appointment appointment) {
        return toAjax(appointmentService.insertAppointment(appointment));
    }

    /**
     * 修改预约记录
     */
    @PreAuthorize("@ss.hasPermi('maincode:appointment:edit')")
    @Log(title = "预约记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Appointment appointment) {
        return toAjax(appointmentService.updateAppointment(appointment));
    }

    /**
     * 删除预约记录
     */
    @PreAuthorize("@ss.hasPermi('maincode:appointment:remove')")
    @Log(title = "预约记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{appointmentIds}")
    public AjaxResult remove(@PathVariable Long[] appointmentIds) {
        return toAjax(appointmentService.deleteAppointmentByAppointmentIds(appointmentIds));
    }


    @Autowired
    private IDoctorScheduledService doctorScheduledService;
    private final Lock lock = new ReentrantLock();

    /**
     * 新增预约记录
     */
    @Log(title = "用户预约", businessType = BusinessType.INSERT)
    @PostMapping("/userAppointment")
    @Transactional(rollbackFor = Exception.class)
    public R userAppointment(@RequestBody Appointment appointment) {
        lock.lock(); // 获取锁
        try {
            DoctorScheduled doctorScheduled = doctorScheduledService.selectDoctorScheduledById(appointment.getDoctorScheduledId());
            if (doctorScheduled.getRemainder() < 1) {
                return R.fail("没有号了");
            }
            appointment.setCreateTime(new Date());
            appointment.setCreateBy(SecurityUtils.getUserId().toString());
            appointment.setPatientId(SecurityUtils.getUserId());
            appointment.setAppointmentStatus(1);
            Random random = new Random();
            appointment.setCode( (random.nextInt(900000) + 100000) + ""); // 生成一个六位数的随机数字
            int insertAppointment = appointmentService.insertAppointment(appointment);
            if (insertAppointment > 0) {
                doctorScheduled.setRemainder(doctorScheduled.getRemainder() - 1);
                doctorScheduledService.updateDoctorScheduled(doctorScheduled);
            }
        } finally {
            lock.unlock(); // 释放锁
        }

        return R.ok("预约成功");
    }



    /**
     * 用户查询自己的预约记录
     * @param appointment
     * @return
     */
    @GetMapping("/getUserAppointment")
    public TableDataInfo getUserAppointment(Appointment appointment) {
        startPage();
        appointment.setPatientId(SecurityUtils.getUserId());
        List<Appointment> list = appointmentService.selectAppointmentList(appointment);
        return getDataTable(list);
    }


    /**
     * 用户查询自己的预约记录
     * @param appointment
     * @return
     */
    @GetMapping("/getUserCommentAppointment")
    public TableDataInfo getUserCommentAppointment(Appointment appointment) {
        startPage();
        appointment.setPatientId(SecurityUtils.getUserId());
        List<Appointment> list = appointmentService.getUserCommentAppointment(appointment);
        return getDataTable(list);
    }


    /**
     * 修改预约记录
     */
    @Log(title = "修改预约记录", businessType = BusinessType.UPDATE)
    @PutMapping("/outpatients")
    public R outpatients(@RequestBody Appointment appointment) {
        Appointment appointment1 = appointmentService.selectAppointmentByAppointmentId(appointment.getAppointmentId());
        if (appointment1.getCode().equals(appointment.getCode())){
            appointment.setAppointmentStatus(3);
            return R.ok(appointmentService.updateAppointment(appointment));
        }
        return R.fail("就诊码错误!");
    }

    /**
     * 查询记录
     * @param appointmentId
     * @return
     */

    @GetMapping(value = "/getAppointment/{appointmentId}")
    public AjaxResult Appointment(@PathVariable("appointmentId") Long appointmentId) {
        return success(appointmentService.selectAppointmentByAppointmentId(appointmentId));
    }

    /**
     * 用户评论
     * @param appointment
     * @return
     */

    @PostMapping("/userComment")
    public R userComment(@RequestBody Appointment appointment) {
            appointment.setAppointmentStatus(5);
            appointment.setCreateBy(SecurityUtils.getUserId().toString());
            return R.ok(appointmentService.updateAppointment(appointment));
    }



}
